package com.sf.dlb.service;


import com.sf.dlb.bean.NewRquestBean;
import com.sf.dlb.config.Global;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.NewRecodInfo;
import com.sf.dlb.jpa.repository.NewRecodRepository;
import com.sf.dlb.mongo.model.NewInfo;
import com.sf.dlb.mongo.model.NewList;
import com.sf.dlb.mongo.repository.NewInfoRepository;
import com.sf.dlb.mongo.repository.NewListRepository;
import com.sf.dlb.utils.DateUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.vo.NewInfoVO;
import com.sf.dlb.vo.PageVO;
import com.sf.dlb.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class NewListService {
    private static Logger logger = LoggerFactory.getLogger(NewListService.class);
    @Autowired
    private Global global;
    @Autowired
    private NewListRepository newListRepository;
    @Autowired
    private NewRecodRepository newRecodRepository;
    @Autowired
    private NewInfoRepository newInfoRepository;
    @Autowired
    private UserShieldService userShieldService;

    /**
     * 查询新闻列表
     *
     * @param newRquestBean
     * @return
     */
    public ResultVO findbyList(NewRquestBean newRquestBean){
        //分页查询
        String userId=newRquestBean.getUserId();
        int currentPages=newRquestBean.getCurrentPages();
        int pageSize=newRquestBean.getPageSize();
        String classId=newRquestBean.getClassId();
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        NewList newListInfo=new NewList();
        newListInfo.setClassId(classId);
        newListInfo.setDelFlag("0");
        Example example=Example.of(newListInfo);
        Pageable pageable = new PageRequest(currentPages,pageSize,sort);
        Page<NewList> newListPage= newListRepository.findAll(example,pageable);
        //过滤用户是否有屏蔽
        List<NewList> newListInfos=userShieldService.newsShieldFilter(userId,newListPage.getContent());
        if(CollectionUtils.isEmpty(newListInfos)) {
            logger.info("findbyList 新闻列表为空 ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"新闻列表为空");
        }
        //客户端最新看到的新闻时间，计算用户这次更新了多少条新闻
        Date createDate=null;
        int refreshCount=-1;
        if(StringUtils.isNoneBlank(newRquestBean.getNewId())){
            NewList newListInfo1=newListRepository.findByIdAndDelFlag(newRquestBean.getNewId(),"0");
            createDate=(null!=newListInfo1?newListInfo1.getCreateDate():null);
            refreshCount=0;
        }
        //封装Vo
        ArrayList<NewInfoVO> dataListBeans=new ArrayList<>();
        PageVO pageVO=new PageVO();
        //查询阅读记录
        List<NewRecodInfo> newRecodInfos= newRecodRepository.findByUserIdAndDelFlag(userId,"0");
        int index=0;
        for (NewList newListInfo1:newListInfos) {
            index++;
            NewInfoVO newInfoVO=new NewInfoVO();
            BeanUtils.copyProperties(newListInfo1,newInfoVO);
            String title=new String(Base64Utils.decodeFromString(newListInfo1.getTitle()));
            newInfoVO.setTitle(title);
            String source=new String(Base64Utils.decodeFromString(newListInfo1.getSource()));
            newInfoVO.setSource(source);
            String label=new String(Base64Utils.decodeFromString(newListInfo1.getLabel()));
            newInfoVO.setLabel(label);
            newInfoVO.setContentId(newListInfo1.getNewInfoId());
            newInfoVO.setGetDlbState(isGetDlb(newRecodInfos,newListInfo1.getId()+""));
            newInfoVO.setReadState(isReadNew(newRecodInfos,newListInfo1.getId()+""));
            newInfoVO.setTime(DateUtils.timeFormatWhatBefore(newListInfo1.getCreateDate()));
            newInfoVO.setNewId(newListInfo1.getId()+"");
            newInfoVO.setViewType((index%5>0)?"0":"1");//4+1，4张小图，1张大图
            newInfoVO.setNewDetailsPageLink(global.new_details_page_link+"?newId="+newListInfo1.getId());
            dataListBeans.add(newInfoVO);
            //计算用户这次更新了多少条新闻
            if(null!=createDate&&newListInfo1.getCreateDate().getTime()>createDate.getTime()){
                refreshCount++;
            }
        }
        //如果没有传newId 默认刷新数=查询数
        if(refreshCount<0){
            refreshCount=dataListBeans.size();
        }
        pageVO.setDataList(dataListBeans);
        pageVO.setPageSize(pageSize);
        pageVO.setCurrentPages(currentPages+1);//默认从0开始，返回前端要+1;
        pageVO.setFirstPage(newListPage.isFirst());
        pageVO.setLastPage(newListPage.isLast());
        pageVO.setTotalElements(newListPage.getTotalElements());
        pageVO.setTotalPages(newListPage.getTotalPages());
        pageVO.setRefreshNumber(refreshCount);
        return ResultVOUtil.success(pageVO);
    }
    /**
     * 查询新闻列表(未登录)
     * @param newRquestBean
     * @return
     */
    public ResultVO findbyListNotLogin(NewRquestBean newRquestBean){
        //分页查询
        int currentPages=newRquestBean.getCurrentPages();
        int pageSize=newRquestBean.getPageSize();
        String classId=newRquestBean.getClassId();
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        NewList newListInfo=new NewList();
        newListInfo.setClassId(classId);
        newListInfo.setDelFlag("0");
        Example example=Example.of(newListInfo);
        Pageable pageable = new PageRequest(currentPages,pageSize,sort);
        Page<NewList> newListPage= newListRepository.findAll(example,pageable);
        List<NewList> newListInfos=newListPage.getContent();
        if(CollectionUtils.isEmpty(newListInfos)) {
            logger.info("findbyList 新闻列表为空 ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"新闻列表为空");
        }
        //查询客户端最新看到的新闻时间，计算用户这次更新了多少条新闻
        Date createDate=null;
        int refreshCount=-1;
        if(StringUtils.isNoneBlank(newRquestBean.getNewId())){
            NewList newListInfo1=newListRepository.findByIdAndDelFlag(newRquestBean.getNewId(),"0");
            createDate=(null!=newListInfo1?newListInfo1.getCreateDate():null);
            refreshCount=0;
        }
        //封装Vo
        ArrayList<NewInfoVO> dataListBeans=new ArrayList<>();
        PageVO pageVO=new PageVO();
        //查询阅读记录
        int index=0;
        for (NewList newListInfo1:newListInfos) {
            index++;
            NewInfoVO newInfoVO=new NewInfoVO();
            BeanUtils.copyProperties(newListInfo1,newInfoVO);
            String title=new String(Base64Utils.decodeFromString(newListInfo1.getTitle()));
            newInfoVO.setTitle(title);
            String source=new String(Base64Utils.decodeFromString(newListInfo1.getSource()));
            newInfoVO.setSource(source);
            String label=new String(Base64Utils.decodeFromString(newListInfo1.getLabel()));
            newInfoVO.setLabel(label);
            newInfoVO.setContentId(newListInfo1.getNewInfoId());
            newInfoVO.setTime(DateUtils.timeFormatWhatBefore(newListInfo1.getCreateDate()));
            newInfoVO.setNewId(newListInfo1.getId()+"");
            newInfoVO.setViewType((index%5>0)?"0":"1");//4+1，4张小图，1张大图
            newInfoVO.setNewDetailsPageLink(global.new_details_page_link+"?newId="+newListInfo1.getId());
            dataListBeans.add(newInfoVO);
            //计算用户这次更新了多少条新闻
            if(null!=createDate&&newListInfo1.getCreateDate().getTime()>createDate.getTime()){
                refreshCount++;
            }
        }
        //如果没有传newId 默认刷新数=查询数
        if(refreshCount<0){
            refreshCount=dataListBeans.size();
        }
        pageVO.setDataList(dataListBeans);
        pageVO.setPageSize(pageSize);
        pageVO.setCurrentPages(currentPages+1);//默认从0开始，返回前端要+1;
        pageVO.setFirstPage(newListPage.isFirst());
        pageVO.setLastPage(newListPage.isLast());
        pageVO.setTotalElements(newListPage.getTotalElements());
        pageVO.setTotalPages(newListPage.getTotalPages());
        pageVO.setRefreshNumber(refreshCount);
        return ResultVOUtil.success(pageVO);
    }
    /**
     * 是否已阅读
     * @param newId
     * @return
     */
    public String isReadNew(List<NewRecodInfo> newRecodInfos, String newId){
        NewRecodInfo newRecodInfo=null;
        for (NewRecodInfo info:newRecodInfos) {
            if(info.getNewId().equals(newId)){
                newRecodInfo=info;
                break;
            }
        }
        return isReadNew(newRecodInfo);
    }
    /**
     * 是否已阅读
     * @return
     */
    public String isReadNew(NewRecodInfo newRecodInfo){
        if(null==newRecodInfo){
            return "0";
        }else{
            return "1";
        }
    }
    /**
     * 是否已领取dlb
     * @return
     */
    public String isGetDlb(NewRecodInfo newRecodInfo){
        if(null==newRecodInfo){
            return "0";
        }else{
            if(StringUtils.isEmpty(newRecodInfo.getGetState())){
                return "0";
            }else if(newRecodInfo.getGetState().equals("0")){
                return "0";
            }else{
                return "1";
            }
        }
    }
    /**
     * 是否已领取dlb
     * @param newId
     * @return
     */
    public String isGetDlb(List<NewRecodInfo> newRecodInfos, String newId){
        NewRecodInfo newRecodInfo=null;
        for (NewRecodInfo info:newRecodInfos) {
            if(info.getNewId().equals(newId)){
                newRecodInfo=info;
                break;
            }
        }
        return isGetDlb(newRecodInfo);
    }
    /**
     * 获取新闻列表详情
     * @param newId
     * @return
     */
    public ResultVO findByNewInfo(String userId,String newId){
        NewList newList= newListRepository.findOne(newId);
        if(null==newList){
            logger.info("findByNewInfo  newListInfo is null  ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"查询数据为空");
        }
        NewInfo newInfo= newInfoRepository.findByIdAndDelFlag(newList.getNewInfoId(),"0");
        if(null==newInfo){
            logger.info("findByNewInfo newInfo is null ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"查询数据为空");
        }
        NewInfoVO newInfoVO=new NewInfoVO();
        BeanUtils.copyProperties(newList,newInfoVO);
        newInfoVO.setNewId(newList.getId());
        //新闻内容解码
        String title=new String(Base64Utils.decodeFromString(newList.getTitle()));
        newInfoVO.setTitle(title);
        String source=new String(Base64Utils.decodeFromString(newList.getSource()));
        newInfoVO.setSource(source);
        String content=new String(Base64Utils.decodeFromString(newInfo.getContent()));
        newInfoVO.setContent(content);
        NewRecodInfo newRecodInfo= newRecodRepository.findByUserIdAndNewIdAndDelFlag(userId,newId,"0");
        newInfoVO.setGetDlbState(isGetDlb(newRecodInfo));
        newInfoVO.setReadState(isReadNew(newRecodInfo));
        String time=StringUtils.isBlank(newList.getTime())?DateUtils.formatDate(newList.getCreateDate(),"yyyy-MM-dd HH:mm:ss"):newList.getTime();
        newInfoVO.setTime(time);
        return ResultVOUtil.success(newInfoVO);
    }
    /**
     * 获取新闻列表详情(未登录)
     * @param newId
     * @return
     */
    public ResultVO findByNewInfoNotLogin(String newId){
        NewList newList= newListRepository.findOne(newId);
        if(null==newList){
            logger.info("findByNewInfo  newListInfo is null  ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"查询数据为空");
        }
        NewInfo newInfo= newInfoRepository.findByIdAndDelFlag(newList.getNewInfoId(),"0");
        if(null==newInfo){
            logger.info("findByNewInfo newInfo is null ");
            return ResultVOUtil.error(ResponseConstant.ERROR,"查询数据为空");
        }
        NewInfoVO newInfoVO=new NewInfoVO();
        BeanUtils.copyProperties(newList,newInfoVO);
        newInfoVO.setNewId(newList.getId());
        //新闻内容解码
        String title=new String(Base64Utils.decodeFromString(newList.getTitle()));
        newInfoVO.setTitle(title);
        String source=new String(Base64Utils.decodeFromString(newList.getSource()));
        newInfoVO.setSource(source);
        String content=new String(Base64Utils.decodeFromString(newInfo.getContent()));
        newInfoVO.setContent(content);
        String time=StringUtils.isBlank(newList.getTime())?DateUtils.formatDate(newList.getCreateDate(),"yyyy-MM-dd HH:mm:ss"):newList.getTime();
        newInfoVO.setTime(time);
        return ResultVOUtil.success(newInfoVO);
    }
}
